//
//  ViewController.swift
//  UI23_LBS2
//
//  Created by yao_yu on 14-9-25.
//  Copyright (c) 2014年 yao_yu. All rights reserved.
//

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var lblPosition: UILabel!
    @IBOutlet weak var mapView: MKMapView!
    
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mapView.delegate = self
        adjustRegion(28.19, aLongitude: 112.98)

        setupLBS()
        addPoint()
    }
    
    func setupLBS(){
        if CLLocationManager.locationServicesEnabled(){
            locationManager.delegate = self
            locationManager.distanceFilter = 200
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
            lblPosition.text = "正在搜索当前位置"
        }
    }
    
    func adjustRegion(aLatitude:CLLocationDegrees, aLongitude: CLLocationDegrees){
        var latitude:CLLocationDegrees = aLatitude
        var longitude:CLLocationDegrees = aLongitude
        var latDelta:CLLocationDegrees = 0.05
        var longDelta:CLLocationDegrees = 0.05
        
        var aSpan:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latDelta,longitudeDelta: longDelta)
        var Center :CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
        var region:MKCoordinateRegion = MKCoordinateRegionMake(Center, aSpan)
        
        self.mapView.setRegion(region, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
        lblPosition.text = newLocation.description
    }
    
    func addPoint(){
        var point = MKPointAnnotation()
        point.coordinate = CLLocationCoordinate2DMake(28.19, 112.98);
        point.title =  "这是一个测试"
        point.subtitle = "磊"
        mapView.addAnnotation(point)
    }
    
    //自定义注释视图
    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
        let placemarkIdentifier = "自定义注释视图";

        var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(placemarkIdentifier)
        if (annotationView == nil) {
            annotationView = MKAnnotationView(annotation:annotation, reuseIdentifier:placemarkIdentifier);
            annotationView.image = UIImage(named:"header.jpg")
            var lblTitle = UILabel(frame: CGRectMake(0, 0, 300, 20))
            lblTitle.text = annotation.title
            annotationView.addSubview(lblTitle)
            annotationView.canShowCallout = true
        }
        
        return annotationView;

    }
}


